<?php

class AuthController extends Zend_Controller_Action
{
    public function preDispatch()
    {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            // If the user is logged in, we don't want to show the login form;
            // however, the logout action should still be available
            if ('logout' != $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index', 'index');
            }
        } else {
            // If they aren't, they can't logout, so that action should
            // redirect to the login form
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index');
            }
        }
    }

    public function indexAction()
    {
        $this->view->form = new Model_Form_Login();
    }

    public function loginAction()
    {
        $request = $this->getRequest();

        if (!$request->isPost()) {
            return $this->_forward('index');
        }

        $form = new Model_Form_Login();

        // Failed validation, redisplay form
        if (!$form->isValid($request->getPost())) {
            $this->view->form = $form;
            return $this->render('index');
        }

        // If auth successfull, $auth does identity persistance
        $appAuthAdapter = $this->getAppAuthAdapter($form->getValues());
        $auth           = Zend_Auth::getInstance()->authenticate($appAuthAdapter);

        // Auth failed
        if (!$auth->isValid()) {
            $form->setDescription('Invalid credentials provided');
            $this->view->form = $form;
            return $this->render('index');
        }

        // We're authenticated! Redirect to the home page
        $this->_helper->redirector('index', 'index');
    }

    public function getAppAuthAdapter($params)
    {
        $adapter = new Model_AppAuthAdapter();
        $adapter
            ->setIdentity($params['username'])
            ->setCredential($params['password']);

        return $adapter;
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index'); // back to login page
    }
}
